package com.xmut.mall.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.text.StrBuilder;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xmut.mall.order.dto.OrderComplaintDTO;
import com.xmut.mall.order.dto.OrderComplaintOperationParams;
import com.xmut.mall.order.dto.OrderComplaintSearchParams;
import com.xmut.mall.order.entity.OrderComplaintCommunicationEntity;
import com.xmut.mall.order.entity.OrderEntity;
import com.xmut.mall.order.entity.OrderItemEntity;
import com.xmut.mall.order.feign.ProductFeignService;
import com.xmut.mall.order.myenum.ComplaintStatusEnum;
import com.xmut.mall.order.myenum.OrderComplaintStatusEnum;
import com.xmut.mall.order.service.OrderComplaintCommunicationService;
import com.xmut.mall.order.service.OrderItemService;
import com.xmut.mall.order.service.OrderService;
import com.xmut.mall.order.utils.PageUtil;
import com.xmut.mall.order.utils.RespBean;
import com.xmut.mall.order.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmut.mall.order.utils.PageUtils;
import com.xmut.mall.order.utils.Query;

import com.xmut.mall.order.dao.OrderComplaintDao;
import com.xmut.mall.order.entity.OrderComplaintEntity;
import com.xmut.mall.order.service.OrderComplaintService;
import org.springframework.transaction.annotation.Transactional;


@Service("orderComplaintService")
public class OrderComplaintServiceImpl extends ServiceImpl<OrderComplaintDao, OrderComplaintEntity> implements OrderComplaintService {

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private OrderComplaintCommunicationService orderComplaintCommunicationService;

    /**
     * 获取当前投诉订单项的id
     * @param itemId
     * @return
     */
    @Override
    public RespBean getOrderComplaintItem(Long itemId) {
        OrderItemEntity entity = orderItemService.getById(itemId);

        return RespBean.success("获取成功",entity);
    }

    /**
     * 添加订单投诉
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespBean addOrderComplaint(OrderComplaintDTO dto) {
        OrderComplaintEntity orderComplaint = new OrderComplaintEntity();
        BeanUtil.copyProperties(dto, orderComplaint);

        // 远程请求获取商品信息
        RespBean skuInfoById = productFeignService.getSkuInfoById(dto.getSkuId());
        if (skuInfoById.getObj() == null){
            return RespBean.error("该商品不存在");
        }
        SkuInfoEntityVo goodsSku = JSON.parseObject(JSON.toJSONString(skuInfoById.getObj()), SkuInfoEntityVo.class);
        Long orderComplaintId = IdWorker.getId();
        orderComplaint.setId(orderComplaintId);
        orderComplaint.setComplainStatus(ComplaintStatusEnum.NEW.name());
        orderComplaint.setGoodsId(goodsSku.getSkuId());
        orderComplaint.setGoodsName(goodsSku.getSkuName());
        orderComplaint.setGoodsImage(goodsSku.getSkuDefaultImg());
        orderComplaint.setGoodsPrice(goodsSku.getPrice());
        orderComplaint.setNum(dto.getItemNum());
        OrderEntity orderEntity = new OrderEntity();
        //获取订单信息
//        OrderEntity orderEntity = orderService.getOne(new QueryWrapper<OrderEntity>().eq("sn", dto.getOrderSn()));
        List<OrderEntity> orderEntityList = orderService.list(new QueryWrapper<OrderEntity>().eq("sn", dto.getOrderSn()));
        if (orderEntityList == null){
            return RespBean.error("订单不存在");
        }else {
            orderEntity = orderEntityList.get(0);
        }
        //获取订单信息
        orderComplaint.setOrderTime(orderEntity.getCreateTime());
        orderComplaint.setOrderPrice(orderEntity.getFlowPrice());
        orderComplaint.setNum(orderEntity.getGoodsNum());
        orderComplaint.setFreightPrice(orderEntity.getFreightPrice());
        orderComplaint.setLogisticsNo(orderEntity.getLogisticsNo());
        orderComplaint.setConsigneeMobile(orderEntity.getConsigneeMobile());
        orderComplaint.setConsigneeAddressPath(orderEntity.getConsigneeAddressPath());
        orderComplaint.setConsigneeName(orderEntity.getConsigneeName());

        //获取商家信息
        orderComplaint.setStoreId(orderEntity.getStoreId());
        orderComplaint.setStoreName(orderEntity.getStoreName());

        // 用户信息
        orderComplaint.setMemberId(orderEntity.getMemberId());
        orderComplaint.setMemberName(orderEntity.getMemberName());
        orderComplaint.setCreateTime(new Date());

        //保存订单投诉
        this.save(orderComplaint);
        //更新订单投诉状态
        orderItemService.updateOrderItemsComplainStatus(dto.getItemId(),dto.getSkuId(),orderComplaintId, OrderComplaintStatusEnum.APPLYING);
        return RespBean.success("保存成功",orderComplaint);
    }

    /**
     * 获取订单投诉的分页数据
     * @param vo
     * @param params
     * @return
     */
    @Override
    public RespBean getOrderComplaintByPage(PageVO vo, OrderComplaintSearchParams params) {
        IPage<OrderComplaintEntity> page = this.baseMapper.getOrderComplaintByPage(PageUtil.initPage(vo), params);

        return RespBean.success("获取成功",page);

    }

    /**
     * 获取交易投诉详情
     * @param id
     * @return
     */
    @Override
    public RespBean getOrderComplaintDetail(Long id) {
        OrderComplaintEntity orderComplaint = this.getById(id);
        if (orderComplaint == null) {
            return RespBean.error("当前投诉不存在");
        }
        List<OrderComplaintCommunicationEntity> list = orderComplaintCommunicationService
                .list(new QueryWrapper<OrderComplaintCommunicationEntity>().eq("complain_id", id));
        OrderComplaintVO orderComplainVO = new OrderComplaintVO(orderComplaint);
        orderComplainVO.setOrderComplaintCommunications(list);
        orderComplainVO.setOrderComplaintImages(orderComplaint.getImages().split(","));
        if (orderComplaint.getAppealImages() != null) {
            orderComplainVO.setAppealImagesList(orderComplaint.getAppealImages().split(","));
        }
        return RespBean.success("获取成功",orderComplainVO);
    }

    /**
     * 取消订单投诉
     * @param id
     * @return
     */
    @Override
    public RespBean cancelOrderComplaint(Long id) {
        OrderComplaintEntity orderComplaint = this.getById(id);
        // 一些前置判断
        if (orderComplaint == null){
            return RespBean.error("当前投诉不存在");
        }
        if (orderComplaint.getComplainStatus().equals(ComplaintStatusEnum.COMPLETE.name())){
            return RespBean.error("申诉已完成，不需要进行取消申诉操作");
        }

        orderComplaint.setComplainStatus(ComplaintStatusEnum.CANCEL.name());
        boolean b = this.updateById(orderComplaint);
        if (b){
            return RespBean.success("取消成功");
        }else {
            return RespBean.error("取消失败");
        }
    }

    /**
     * 修改状态
     * @param params
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateOrderComplainByStatus(OrderComplaintOperationParams params) {
        OrderComplaintEntity orderComplaint = this.getById(params.getComplainId());
        if (orderComplaint==null){
            throw new RuntimeException("当前投诉单不存在");
        }
        this.checkOperationParams(params, orderComplaint);
        orderComplaint.setComplainStatus(params.getComplainStatus());
        boolean b = this.updateById(orderComplaint);
        if (!b){
            throw new RuntimeException("修改状态失败");
        }
    }

    /**
     * 商家申诉
     * @param vo
     * @return
     */
    @Override
    public RespBean appeal(StoreAppealVO vo) {
        OrderComplaintEntity orderComplaint = this.getById(vo.getOrderComplaintId());
        if (orderComplaint==null){
            return RespBean.error("当前投诉单不存在");
        }
        orderComplaint.setAppealContent(vo.getAppealContent());
        StrBuilder sb = new StrBuilder();
        for (String appealImage : vo.getAppealImages()) {
            sb.append(appealImage);
            sb.append(",");
        }
        orderComplaint.setAppealImages(sb.toString());
        orderComplaint.setAppealTime(new Date());
        orderComplaint.setComplainStatus(ComplaintStatusEnum.WAIT_ARBITRATION.name());
        boolean b = this.updateById(orderComplaint);
        if (b){
            return RespBean.success("申诉成功");
        }else {
            return RespBean.error("申诉失败");
        }
    }

    private void checkOperationParams(OrderComplaintOperationParams operationParam, OrderComplaintEntity orderComplaint) {
        ComplaintStatusEnum complaintStatusEnum = ComplaintStatusEnum.valueOf(operationParam.getComplainStatus());
        if (complaintStatusEnum == ComplaintStatusEnum.COMPLETE) {
            if (CharSequenceUtil.isEmpty(operationParam.getArbitrationResult())) {
                throw new RuntimeException("当前投诉记录不存在");
            }
            orderComplaint.setArbitrationResult(operationParam.getArbitrationResult());
        } else if (complaintStatusEnum == ComplaintStatusEnum.COMMUNICATION) {
            if (CharSequenceUtil.isEmpty(operationParam.getAppealContent()) || operationParam.getImages() == null) {
                throw new RuntimeException("商家申诉时，申诉内容不能为空");
            }
            orderComplaint.setContent(operationParam.getAppealContent());
            orderComplaint.setImages(operationParam.getImages().get(0));
        }
    }


}